import os, sys
import Image
import ImageEnhance
import ImageFilter
import ImageDraw
import ImageOps
import scipy.ndimage
import time
from numpy import *

def cart2polar(grid, center, radius):
    result = zeros((720, radius))
    s = grid.shape
    print "center", center
    for phi in range(720):
        for r in range(radius):
            x = int(r*math.cos(phi*math.pi/360.)+center[0])
            y = int(r*math.sin(phi*math.pi/360.)+center[1])
            if x < s[0] and x >=0 and y < s[1] and y >=0:
                result[phi,r] = 255*grid[x,y]
    return result
    
def minEdge(grid):
    result = zeros(grid.shape[0])
    for x in range(grid.shape[0]):
        for y in range(grid.shape[1]):    
            if grid[x,y] > 0:
                result[x] = y
    return result

def polarEdge2cart(edge, size, center):
    result = zeros(size)
    for phi in range(edge.size):
        x = int(edge[phi]*math.cos(phi*math.pi/360.)+center[0])
        y = int(edge[phi]*math.sin(phi*math.pi/360.)+center[1])
        if x < size[0] and x >=0 and y < size[1] and y >=0:
            result[x,y] = 255
    return result
        

if len(sys.argv) < 2:
    print "Usage: python ", sys.argv[0], " <image_file_name>[,<output_dir>]."
else:
    start = time.clock()

    filename = str(sys.argv[1])
    im = Image.open(filename)
    outputDir = ""
    
    if len(sys.argv) > 2 :
        outputDir = str(sys.argv[2]) + "/"
        
    print "loading image ", filename, "... " ,

    enhancer = ImageEnhance.Color(im)

    imGray = im.convert("L").resize((500,500), Image.ANTIALIAS).filter(ImageFilter.MedianFilter(9))

    brightness = ImageEnhance.Brightness(imGray)
    imGray = brightness.enhance(0.5)

    contrast = ImageEnhance.Contrast(imGray)
    imGray = ImageOps.equalize(contrast.enhance(2.0))

    print "done."

   
    print "calculationg median point... ",

    grayPix = imGray.load()
    weights = 0.
    coords = []
    imFin = Image.open(filename).convert("RGB").resize((500,500), Image.ANTIALIAS)
    pix = imFin.load()
    for x in range(imFin.size[0]):
        for y in range(imFin.size[1]):
            weight = (grayPix[x,y]/256.)**8
            pix[x,y] = (int(weight * 256), int(weight * 256), int(weight * 256))
            #if pix[x,y] > 0:
            weights+=weight
            #pix[y,x] = (255, 0, 0)
            coords.append((weight*x,weight*y))

    av = (sum([x[0] for x in coords])/weights, sum([x[1] for x in coords])/weights)

    pix[int(av[1]), int(av[0])] = (0,255,0)
    draw = ImageDraw.Draw(imFin)
    draw.arc((int(av[1])-10, int(av[0])-10, int(av[1])+10, int(av[0])+10), 0, 360, "rgb(0,255,0)")

    print "done."
    
    outputName = outputDir + filename.split("/")[len(filename.split("/"))-1].split(".")[0] + "_seg.png"

    print "saving output in ", outputName ,"... ",
    imFin.save(outputName)
    print "done."
    stop = time.clock()
    print "time:", int(stop - start), "s"

